<template>
  <div class="personal-info-container">
    <el-card shadow="hover" class="info-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">个人信息</span>
        </div>
      </template>

      <div class="profile-content">
        <div class="avatar-section">
          <el-image :src="avatarStore.currentAvatar" class="avatar-img" />
          <div class="avatar-actions">
            <el-button type="primary" size="small" plain @click="changeAvatarRandomly">
              <el-icon><Refresh /></el-icon>
              随机头像
            </el-button>
          </div>
        </div>

        <div class="info-section">
          <el-descriptions :column="1" :border="true">
            <el-descriptions-item label="用户名">
              <div class="info-value">{{ userData.username }}</div>
            </el-descriptions-item>

            <el-descriptions-item label="账号">
              <div class="info-value">{{ userData.account }}</div>
            </el-descriptions-item>

            <el-descriptions-item label="注册时间">
              <div class="info-value">
                <span v-if="userData.addTime">{{ formatTime(userData.addTime) }}</span>
                <span v-else>未获取到注册时间</span>
              </div>
            </el-descriptions-item>

            <el-descriptions-item label="账户状态">
              <el-tag type="success" effect="light">正常</el-tag>
            </el-descriptions-item>

            <el-descriptions-item label="认证令牌">
              <el-input v-model="userData.token" readonly class="token-input">
                <template #append>
                  <el-button @click="copyToken">
                    <el-icon><DocumentCopy /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <div class="action-buttons">
        <el-button type="primary" @click="showEditDialog">
          <el-icon><Edit /></el-icon>
          更改信息
        </el-button>
        <el-button type="danger" @click="confirmLogout">
          <el-icon><SwitchButton /></el-icon>
          退出登录
        </el-button>
      </div>
    </el-card>

    <!-- 修改信息对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改信息"
      width="40%"
      :destroy-on-close="true"
      :before-close="handleDialogClose"
    >
      <el-tabs v-model="activeTab">
        <el-tab-pane label="修改用户名" name="username">
          <el-form
            ref="usernameForm"
            :model="editForm"
            :rules="usernameRules"
            label-width="100px"
            @submit.prevent="updateUserInfo"
          >
            <el-form-item label="当前用户名">
              <el-input v-model="userData.username" disabled />
            </el-form-item>
            <el-form-item label="新用户名">
              <el-input v-model="editForm.username" placeholder="输入新用户名" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" native-type="submit" :loading="editLoading">
                <el-icon><Edit /></el-icon>
                更新用户名
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="修改密码" name="password">
          <el-form
            ref="passwordForm"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
            @submit.prevent="changePassword"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model.trim="passwordForm.oldPassword"
                type="password"
                show-password
                placeholder="输入原密码"
                clearable
                :maxlength="20"
                @input="handlePasswordInput('oldPassword')"
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model.trim="passwordForm.newPassword"
                type="password"
                show-password
                placeholder="输入新密码"
                clearable
                :maxlength="20"
                @input="handlePasswordInput('newPassword')"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" native-type="submit" :loading="passwordLoading">
                <el-icon><Key /></el-icon>
                修改密码
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, onMounted } from 'vue'
  import { getUserDetail, setAuthToken, clearAuthTokens } from '@/api/userApi'
  import { useRouter } from 'vue-router'
  import { SwitchButton } from '@element-plus/icons-vue'
  import { useAvatarStore } from '@/stores/avatarStore'
  import defaultAvatar from '@/assets/pig.jpg'
  import avatar1 from '@/assets/ava1.png'
  import avatar2 from '@/assets/ava2.png'
  import avatar3 from '@/assets/ava3.png'
  import avatar4 from '@/assets/ava4.png'
  import { Key, Refresh } from '@element-plus/icons-vue'
  // 导入 userApi 及其方法
  import * as userApi from '@/api/userApi'

  const userData = ref({})
  const loading = ref(true)
  const error = ref(null)
  const router = useRouter()
  // 所有可用头像数组
  const avatarList = [avatar1, avatar2, avatar3, avatar4, defaultAvatar]
  const currentAvatar = ref(defaultAvatar)

  const avatarStore = useAvatarStore()

  // 格式化时间戳为日期时间字符串
  const formatTime = (timestamp) => {
    if (!timestamp || isNaN(timestamp)) {
      console.log('无效的时间戳:', timestamp)
      return '未知'
    }

    try {
      const date = new Date(timestamp)

      // 验证时间戳是否有效
      if (isNaN(date.getTime())) {
        console.log('无效的日期对象，时间戳:', timestamp)
        return '未知'
      }

      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      })
    } catch (e) {
      console.error('时间格式化错误:', e)
      return '未知'
    }
  }

  // 复制Token
  const copyToken = () => {
    if (!userData.value.token) {
      ElMessage.warning('没有可复制的Token')
      return
    }

    navigator.clipboard.writeText(userData.value.token)
    ElNotification.success({
      title: '复制成功',
      message: 'Token已复制到剪贴板',
      duration: 2000,
    })
  }

  // 随机更换头像函数
  const changeAvatarRandomly = () => {
    // 过滤当前头像
    const availableAvatars = avatarStore.avatarList.filter((avatar) => avatar !== avatarStore.currentAvatar)

    if (availableAvatars.length > 0) {
      const randomIndex = Math.floor(Math.random() * availableAvatars.length)
      avatarStore.setAvatar(availableAvatars[randomIndex])
      ElMessage.success('头像已更换')
    } else {
      // 如果只有一个头像，则直接随机选择
      const randomIndex = Math.floor(Math.random() * avatarList.length)
      currentAvatar.value = avatarList[randomIndex]
    }
  }

  // 退出登录确认
  const confirmLogout = () => {
    ElMessageBox.confirm('确定要退出登录吗？此操作将会清除所有登录数据。', '退出登录确认', {
      confirmButtonText: '确定退出',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
      customClass: 'logout-confirm-box',
      icon: markRaw(SwitchButton) ? undefined : 'el-icon-warning',
      dangerouslyUseHTMLString: true,
    })
      .then(() => {
        logout()
      })
      .catch(() => {
        ElMessage.info('已取消退出操作')
      })
  }

  // 退出登录
  const logout = () => {
    clearAuthTokens()
    localStorage.removeItem('userId')
    localStorage.removeItem('username')
    sessionStorage.removeItem('username')

    ElNotification({
      title: '已退出登录',
      message: '您已成功退出系统',
      type: 'success',
      duration: 2000,
    })

    setTimeout(() => {
      router.push('/login')
    }, 800)
  }

  // 添加表单数据和方法
  const usernameForm = ref(null)
  const passwordForm = ref({
    oldPassword: '',
    newPassword: '',
  })
  const editForm = ref({
    username: '',
  })
  const editLoading = ref(false)
  const passwordLoading = ref(false)
  const editDialogVisible = ref(false)
  const activeTab = ref('username')

  // 初始化编辑表单
  const initEditForm = () => {
    if (userData.value && userData.value.username) {
      editForm.value.username = userData.value.username
    }
  }

  // 获取用户详情后调用初始化
  onMounted(async () => {
    try {
      // 从localStorage获取用户ID
      const userId = localStorage.getItem('userId')

      // 严格验证用户ID
      if (!userId) {
        throw new Error('用户ID不存在，请先登录')
      }

      // 转换为数字并验证有效性
      const numericUserId = Number(userId)
      if (isNaN(numericUserId) || !Number.isInteger(numericUserId) || numericUserId <= 0) {
        throw new Error('无效的用户ID')
      }

      // 设置Token到请求头
      const token = localStorage.getItem('token') || sessionStorage.getItem('token')
      if (token) {
        setAuthToken(token)
      }

      // 使用验证后的用户ID调用API
      const data = await getUserDetail(numericUserId)
      // console.log('获取的用户详情data = ', data) // 调试用

      // 初始化头像列表
      avatarStore.avatarList = [avatar1, avatar2, avatar3, avatar4, defaultAvatar]
      avatarStore.initAvatar()

      // 更新组件数据
      userData.value = data
      // 从存储中获取 token
      userData.value.token = localStorage.getItem('token') || sessionStorage.getItem('token') || ''

      // 初始化编辑表单
      initEditForm()
    } catch (error) {
      if (error.message === '非法操作') {
        // 跳转到登录页
        setTimeout(() => {
          window.location.href = '/login'
        }, 3000)
        return
      }

      console.error('获取用户信息失败:', error.message)
      error.value = error.message

      // 显示错误消息
      ElMessage({
        message: '获取用户信息失败: ' + error.message,
        type: 'error',
      })

      // 清除无效的用户ID
      localStorage.removeItem('userId')

      // 跳转到登录页
      setTimeout(() => {
        window.location.href = '/login'
      }, 2000)
    } finally {
      loading.value = false
    }
  })

  // 显示编辑对话框
  const showEditDialog = () => {
    editDialogVisible.value = true
    activeTab.value = 'username'
    // 重置表单
    editForm.value = { username: userData.value.username }
    passwordForm.value = { oldPassword: '', newPassword: '' }
  }

  // 更新用户信息
  const updateUserInfo = async () => {
    if (!editForm.value.username.trim()) {
      ElMessage.warning('用户名不能为空')
      return
    }

    editLoading.value = true
    try {
      const result = await userApi.updateUserInfo(userData.value.id, editForm.value.username)
      if (result) {
        // 只更新用户名，保留其他字段
        userData.value.username = editForm.value.username
        // 更新头像显示（如果需要）
        avatarStore.initAvatar(editForm.value.username)
        // 关闭对话框
        editDialogVisible.value = false
        // 提示用户
        ElNotification.success({
          title: '更新成功',
          message: '您的用户名已更新',
          duration: 2000,
        })
      }
    } catch (error) {
      console.error('更新用户信息失败:', error)
      ElMessage.error('更新失败，请检查您的网络连接')
    } finally {
      editLoading.value = false
    }
  }

  // 修改密码
  const changePassword = async () => {
    if (!passwordForm.value.oldPassword || !passwordForm.value.newPassword) {
      ElMessage.warning('请填写所有密码字段')
      return
    }

    // console.log('旧密码 = ', passwordForm.value.oldPassword)
    // console.log('新密码 = ', passwordForm.value.newPassword)
    passwordLoading.value = true
    try {
      const success = await userApi.changePassword(
        userData.value.id,
        passwordForm.value.oldPassword,
        passwordForm.value.newPassword
      )
      if (success) {
        // 清空表单
        passwordForm.value.oldPassword = ''
        passwordForm.value.newPassword = ''
        // 关闭对话框
        editDialogVisible.value = false
        // 提示用户
        ElNotification.success({
          title: '密码修改成功',
          message: '建议您使用新密码重新登录',
          duration: 3000,
        })
      }
    } catch (error) {
      console.error('修改密码失败:', error)
      ElMessage.error('密码修改失败，请稍后再试')
    } finally {
      passwordLoading.value = false
    }
  }

  const usernameRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' },
    ],
  }

  const passwordRules = {
    oldPassword: [
      { required: true, message: '请输入原密码', trigger: 'blur' },
      { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' },
    ],
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' },
    ],
  }

  const handleDialogClose = (done) => {
    // 重置表单
    editForm.value = { username: userData.value.username }
    passwordForm.value = { oldPassword: '', newPassword: '' }
    done()
  }
  const handlePasswordInput = (field) => {
    // 确保输入值完整传递
    // console.log(`实时 ${field} = `, passwordForm.value[field])
    // 强制更新视图
    passwordForm.value = { ...passwordForm.value }
  }
</script>

<style scoped>
  .personal-info-container {
    padding: 20px;
    max-width: 1000px;
    margin: 0 auto;
  }

  .info-card {
    border-radius: 12px;
    overflow: hidden;
    border: 1px solid #eee;
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
  }

  .header-title {
    font-size: 1.4rem;
    font-weight: 600;
    color: #1e90ff;
  }

  .profile-content {
    display: flex;
    flex-wrap: wrap;
    gap: 30px;
    margin-bottom: 20px;
  }

  .avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    flex: 0 0 200px;
  }

  .avatar-img {
    width: 150px;
    height: 150px;
    border-radius: 8px;
    border: 1px solid #eee;
    background-color: #f8f8f8;
  }

  .avatar-actions {
    margin-top: 15px;
    text-align: center;
  }

  .info-section {
    flex: 1;
    min-width: 300px;
  }

  .info-value {
    padding: 4px 0;
    font-weight: 500;
  }

  .token-input {
    max-width: 500px;
  }

  .action-buttons {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #f0f0f0;
  }

  @media (max-width: 768px) {
    .profile-content {
      flex-direction: column;
      align-items: center;
    }

    .avatar-section {
      margin-bottom: 20px;
    }

    .action-buttons {
      flex-direction: column;
      align-items: center;
    }

    .action-buttons > .el-button {
      width: 100%;
      max-width: 300px;
    }
  }
</style>

<style>
  /* 自定义登出提示框样式 */
  .logout-confirm-box {
    border-radius: 12px;
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  }

  .logout-confirm-box .el-message-box__title {
    font-size: 1.2rem;
    font-weight: 600;
    color: #f56c6c; /* 修改标题颜色为橙红色，更醒目 */
  }

  .logout-confirm-box .el-message-box__content {
    font-size: 1rem;
    color: #333;
    padding: 20px;
  }

  .logout-confirm-box .el-message-box__btns {
    padding: 20px;
    text-align: center;
  }

  .logout-confirm-box .el-button--primary {
    background-color: #f56c6c; /* 修改确认按钮背景色为橙红色 */
    border-color: #f56c6c;
  }

  .logout-confirm-box .el-button--primary:hover {
    background-color: #f56c6c; /* 鼠标悬停时确认按钮背景色变浅 */
    border-color: #f56c6c;
  }

  .logout-confirm-box .el-button--default {
    color: #f56c6c; /* 修改取消按钮文字颜色为橙红色 */
    border-color: #f56c6c;
  }

  .logout-confirm-box .el-button--default:hover {
    background-color: #fff5ee; /* 鼠标悬停时取消按钮背景色变浅 */
    border-color: #f56c6c;
  }

  /* 如果有图标，可以调整图标的颜色 */
  .logout-confirm-box .el-message-box__icon {
    color: #f56c6c;
  }

  @supports (backdrop-filter: blur(10px)) or (-webkit-backdrop-filter: blur(10px)) {
    .logout-confirm-box {
      backdrop-filter: blur(10px);
      -webkit-backdrop-filter: blur(10px);
    }
  }
</style>
